package com.yanqu.road.server.manger.activity.unionwar;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eMallCategory;
import com.yanqu.road.entity.enums.eUnionWarRankConditionType;
import com.yanqu.road.entity.rank.UnionActivityRank;
import com.yanqu.road.entity.unionwar.UnionWarChampionUnionInfo;
import com.yanqu.road.logic.bussiness.activity.UnionWarActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.CrossRankPb;
import com.yanqu.road.logic.pb.RankPb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.sort.UnionActivityRankSort;
import com.yanqu.road.pb.activity.unionwar.CrossUnionWarProto;
import com.yanqu.road.pb.rank.UnionActivityRankProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.unionwar.UnionWarActivityModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 商会战-活动管理
 */
public class UnionWarActivityMgr extends TempMgr {
    protected static Logger logger = LogManager.getLogger(UnionWarActivityMgr.class.getName());
    private static Map<Integer, ActivityInfo> activityInfoMap;
    private static Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap;
    public static Map<Integer, Map<Integer, List<ActivityConditionInfo>>> activityConditionInfoTypeMap;
    public static Map<Integer, Map<Integer, MallInfo>> activityMallInfoMap;
    public static Map<Integer, Map<String, ActivityConfig>> activityConfigMap;
    //weekId activityId  groupId
    private static Map<Integer, Map<Integer, Map<Integer, UnionWarChampionUnionInfo>>> unionWarChampionMap;
    private static CrossUnionWarProto.UnionWarChampionSyncMsg.Builder championMsgBuilder;  //历届冠军列表
    private static UnionActivityRankProto.UnionActivityRankListMsg.Builder championRankBuilder;  //冠军榜
    private static ChampionUnionSort sort;
    //积分赛排行
    public static int CONDITION_TYPE_INTEGRAL_RANK = 1000;
    //决赛排行
    public static int CONDITION_TYPE_FINAL_RANK = 1001;
    //积分赛竞猜
    public static int CONDITION_TYPE_INTEGRAL_GUESS = 1002;
    //决赛竞猜
    public static int CONDITION_TYPE_FINAL_GUESS = 1003;

    public static void syncChampionListMsg() {
        CrossUnionWarProto.UnionWarChampionSyncMsg.Builder builder = CrossUnionWarProto.UnionWarChampionSyncMsg.newBuilder();
        for (Map.Entry<Integer, Map<Integer, Map<Integer, UnionWarChampionUnionInfo>>> entry : unionWarChampionMap.entrySet()) {
            CrossUnionWarProto.UnionWarChampionListTemp.Builder championListTemp = CrossUnionWarProto.UnionWarChampionListTemp.newBuilder();
            championListTemp.setTimeMark(entry.getKey());
            List<UnionWarChampionUnionInfo> championList = new ArrayList<>();
            for (Map.Entry<Integer, Map<Integer, UnionWarChampionUnionInfo>> mapEntry : entry.getValue().entrySet()) {
                for (Map.Entry<Integer, UnionWarChampionUnionInfo> infoEntry : mapEntry.getValue().entrySet()) {
                    championList.add(infoEntry.getValue());
                }
            }
            championList.sort(sort);
            for (UnionWarChampionUnionInfo champion : championList) {
                championListTemp.addChampion(parseChampionTemp(champion));
            }
            builder.addChampion(championListTemp);
        }
        buildChampionMsg(builder.build());
    }

    public static CrossUnionWarProto.UnionWarChampionTemp.Builder parseChampionTemp(UnionWarChampionUnionInfo champion) {
        CrossUnionWarProto.UnionWarChampionTemp.Builder championTemp = CrossUnionWarProto.UnionWarChampionTemp.newBuilder();
        championTemp.setTimeMark(champion.getTimeMark());
        championTemp.setActivityId(champion.getActivityId());
        championTemp.setUnionUid(champion.getUnionUid());
        championTemp.addAllServerId(StringUtils.stringToLongList(champion.getServerIdList(), ","));
        championTemp.setUnionBaseTemp(UnionBasePb.parseUnionBaseTempMsg(champion.getUnionBaseInfo()));
        championTemp.setGroupId(champion.getGroupId());
        return championTemp;
    }

    public static CrossUnionWarProto.UnionWarChampionSyncMsg.Builder getChampionMsgBuilder() {
        return championMsgBuilder;
    }

    public static UnionActivityRankProto.UnionActivityRankListMsg.Builder getChampionRankBuilder() {
        if(championRankBuilder == null){
            return UnionActivityRankProto.UnionActivityRankListMsg.newBuilder();
        }
        return championRankBuilder;
    }

    /**
     * 检查增加冠军商会
     */
    public static void checkAddChampion() {
        for (UnionWar unionWar : UnionPhaseWarMgr.getUnionWarMap().values()) {
            //领奖期去请求
            if (unionWar.checkInGetRewardTime(2)) {
                if (unionWarChampionMap.containsKey(getTimeMark())) {
                    if (unionWarChampionMap.get(getTimeMark()).containsKey(unionWar.getActivityInfo().getActivityId())) {
                        continue;
                    }
                }

                List<Integer> groupIdList = UnionWar.getGroupListByServerId(unionWar.getActivityInfo().getActivityId(), GameServer.getInstance().getServerId());
                for (int groupId : groupIdList) {
                    CrossUnionWarProto.CrossAddChampionReqMsg.Builder respMsg = CrossUnionWarProto.CrossAddChampionReqMsg.newBuilder();
                    respMsg.setActivityId(unionWar.getActivityInfo().getActivityId());
                    respMsg.setGroupId(groupId);
                    //发送跨服请求
                    //YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_WAR_REQ_CHAMPION_ADD, respMsg);
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_UNION_WAR_REQ_CHAMPION_ADD, respMsg, 0, unionWar.getActivityInfo().getActivityId(), groupId);
                }

            }
        }
    }

    /**
     * 游戏服重启同步一次跨服数据
     */
    public static boolean syncConditionAchieveInfoMap() {
        try {
            for (UnionWar unionWar : UnionPhaseWarMgr.getUnionWarMap().values()) {
                unionWar.syncConditionAchieveInfoMap();
            }
            return true;
        } catch (Exception e) {
            logger.error("union war activity sync achieveInfo task error:", e);
            return false;
        }
    }

    private static int getTimeMark() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String monthStr = month < 10 ? "0" + month : month + "";
        String timeStr = year + monthStr;
        return Integer.valueOf(timeStr);
    }

    @Override
    public boolean reloadData() throws Exception {
        unionWarChampionMap = UnionWarActivityBusiness.getServerUnionWarChampionMap();
        sort = new ChampionUnionSort();
        syncChampionListMsg();
        return true;
    }

    /**
     * 游戏服新增冠军商会
     * @param msg
     */
    public static void addChampion(CrossUnionWarProto.UnionWarChampionSyncListMsg msg) {
        synchronized (unionWarChampionMap) {
            for (CrossUnionWarProto.UnionWarChampionTemp unionWarChampionTemp : msg.getChampionList()) {
                if (!unionWarChampionMap.containsKey(unionWarChampionTemp.getTimeMark())) {
                    unionWarChampionMap.put(unionWarChampionTemp.getTimeMark(), new ConcurrentHashMap<>());
                }
                if (!unionWarChampionMap.get(unionWarChampionTemp.getTimeMark()).containsKey(unionWarChampionTemp.getActivityId())) {
                    unionWarChampionMap.get(unionWarChampionTemp.getTimeMark()).put(unionWarChampionTemp.getActivityId(), new ConcurrentHashMap<>());
                }
                if (!unionWarChampionMap.get(unionWarChampionTemp.getTimeMark()).get(unionWarChampionTemp.getActivityId()).containsKey(unionWarChampionTemp.getGroupId())) {
                    UnionWarChampionUnionInfo champion = new UnionWarChampionUnionInfo();
                    champion.setTimeMark(unionWarChampionTemp.getTimeMark());
                    champion.setActivityId(unionWarChampionTemp.getActivityId());
                    champion.setServerIdList(StringUtils.listToString(unionWarChampionTemp.getServerIdList(), ","));
                    champion.setUnionBaseInfo(UnionBasePb.parseUnionBaseInfo(unionWarChampionTemp.getUnionBaseTemp()));
                    champion.setUnionUid(unionWarChampionTemp.getUnionUid());
                    champion.setGroupId(unionWarChampionTemp.getGroupId());
                    champion.setInsertOption();
                    unionWarChampionMap.get(unionWarChampionTemp.getTimeMark()).get(unionWarChampionTemp.getActivityId()).put(unionWarChampionTemp.getGroupId(), champion);
                    syncChampionListMsg();
                }
            }
        }
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map.Entry<Integer, Map<Integer, Map<Integer, UnionWarChampionUnionInfo>>> weekEntry : unionWarChampionMap.entrySet()) {
            for (Map.Entry<Integer, Map<Integer, UnionWarChampionUnionInfo>> activityEntry : weekEntry.getValue().entrySet()) {
                for (Map.Entry<Integer, UnionWarChampionUnionInfo> infoEntry : activityEntry.getValue().entrySet()) {
                    UnionWarChampionUnionInfo info = infoEntry.getValue();
                    if (info.isInsertOption()) {
                        UnionWarActivityBusiness.addServerUnionWarChampionMap(info);
                    }
                }
            }
        }
        return true;
    }

    public static void reloadActivityData(Map<Integer, ActivityInfo> normalActivityInfoMap, Map<Integer, List<ActivityConditionInfo>> selectActivityConditionInfoMap, Map<Integer, Map<Integer, List<ActivityConditionInfo>>> selectActivityConditionInfoTypeMap, Map<Integer, Map<Integer, MallInfo>> selectActivityMallInfoMap,
                                          Map<Integer, Map<String, ActivityConfig>> allActivityConfigMap) {
        getLogger().info("reload unionwar start");

        // 获取商战活动
        Map<Integer,ActivityInfo> tempActivityMap = new ConcurrentHashMap<>();
        Map<Integer, List<ActivityConditionInfo>> tempActivityConditionInfoMap = new ConcurrentHashMap<>();
        Map<Integer, Map<Integer, List<ActivityConditionInfo>>> tempActivityConditionInfoTypeMap = new ConcurrentHashMap<>();
        Map<Integer, Map<Integer, MallInfo>> tempActivityMallInfoMap = new ConcurrentHashMap<>();
        Map<Integer, Map<String, ActivityConfig>> tempActivityConfigInfoMap = new ConcurrentHashMap<>();
        for (ActivityInfo tmpActivityInfo : normalActivityInfoMap.values()) {
            if (tmpActivityInfo.getType() == eActivityType.CrossUnionWarActivity.getValue()) {
                if (ActivityMgr.activityInShowTime(tmpActivityInfo)) {
                    tempActivityMap.put(tmpActivityInfo.getActivityId(), tmpActivityInfo);
                    if (selectActivityConditionInfoMap.containsKey(tmpActivityInfo.getActivityId())) {
                        tempActivityConditionInfoMap.put(tmpActivityInfo.getActivityId(), selectActivityConditionInfoMap.get(tmpActivityInfo.getActivityId()));
                    }
                    if (selectActivityConditionInfoTypeMap.containsKey(tmpActivityInfo.getActivityId())) {
                        tempActivityConditionInfoTypeMap.put(tmpActivityInfo.getActivityId(), selectActivityConditionInfoTypeMap.get(tmpActivityInfo.getActivityId()));
                    }
                    if (selectActivityMallInfoMap.containsKey(tmpActivityInfo.getActivityId())) {
                        tempActivityMallInfoMap.put(tmpActivityInfo.getActivityId(), selectActivityMallInfoMap.get(tmpActivityInfo.getActivityId()));
                    }
                    if (allActivityConfigMap.containsKey(tmpActivityInfo.getActivityId())){
                        tempActivityConfigInfoMap.put(tmpActivityInfo.getActivityId(), allActivityConfigMap.get(tmpActivityInfo.getActivityId()));
                    }
                    break;//限制每次只取第一个活动
                }
            }
        }
        activityInfoMap = tempActivityMap;
        activityMallInfoMap = tempActivityMallInfoMap;
        activityConditionInfoMap = tempActivityConditionInfoMap;
        activityConditionInfoTypeMap = tempActivityConditionInfoTypeMap;
        activityConfigMap = tempActivityConfigInfoMap;

        UnionPhaseWarMgr.reload(activityInfoMap, activityMallInfoMap, UnionWarActivityMgr.activityConditionInfoTypeMap);

        playerReloadActivity();

        getLogger().info("reload unionWar end");
    }

    public static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(player ->{
            UnionWarActivityModule activityModule = player.getModule(UnionWarActivityModule.class);
            activityModule.syncActivity();
        });
    }


    public static Map<Integer, ActivityInfo> getActivityInfoMap() {
        return activityInfoMap;
    }

    public static ActivityInfo getOpenActivityInfo(int activityId){
        if(!activityInfoMap.containsKey(activityId)){
            return null;
        }
        ActivityInfo activityInfo = activityInfoMap.get(activityId);
        if(ActivityMgr.activityInShowTime(activityInfo) && activityInfo.getActivityId() == activityId){
            return activityInfo;
        }
        return null;
    }

    public static Map<Integer, ActivityInfo> getOpenActivityInfoMap() {
        Map<Integer, ActivityInfo> openActivityInfoMap = new ConcurrentHashMap<>();
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            if (ActivityMgr.activityInShowTime(activityInfo)) {
                openActivityInfoMap.put(activityInfo.getActivityId(), activityInfo);
            }
        }
        return openActivityInfoMap;
    }

    public static List<ActivityInfo> getOpenActivityInfo(){
        List<ActivityInfo> activityInfoList = new ArrayList<>();
        for(int activityId : activityInfoMap.keySet()){
            ActivityInfo activityInfo = activityInfoMap.get(activityId);
            if(ActivityMgr.activityInShowTime(activityInfo)){
                activityInfoList.add(activityInfo);
            }
        }
        return activityInfoList;
    }

    public static Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfoMap() {
        return activityConditionInfoMap;
    }

    public static Map<Integer, Map<Integer, MallInfo>> getActivityMallInfoMap() {
        return activityMallInfoMap;
    }

    public static Map<Integer, Map<String, ActivityConfig>> getActivityConfigMap() {
        return activityConfigMap;
    }

    public static MallInfo getActivityMallInfo(int activityId, int mallId){
        Map<Integer, MallInfo> mallInfoMap = activityMallInfoMap.get(activityId);
        if(null != mallInfoMap){
            return mallInfoMap.get(mallId);
        }
        return null;
    }

    /**
     * 获取阶段对应的排行榜conditionType
     * @param phase 阶段
     * @return 条件类型
     */
    public static int getConditionTypeByPhase(int phase) {
        for (eUnionWarRankConditionType value : eUnionWarRankConditionType.values()) {
            if (value.getPhase() == phase) {
                return value.getConditionType();
            }
        }
        return 0;
    }

    /**
     * 获取排行榜conditionType对应的阶段
     * @param conditionType 条件类型
     * @return 阶段
     */
    public static int getPhaseByConditionType(int conditionType) {
        for (eUnionWarRankConditionType value : eUnionWarRankConditionType.values()) {
            if (value.getConditionType() == conditionType) {
                return value.getPhase();
            }
        }
        return 0;
    }

    /**
     * 获取活动配置的最大名次
     */
    public static int getMaxRank(int activityId, int conditionType){
        int maxRank = GameConfig.RANK_DEFAULT_MAX_COUNT;
        ActivityInfo activityInfo = getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            maxRank = ActivityHelper.getMaxRankByConditionType(conditionType, getActivityConditionInfoMap().get(activityId));
        }
        return maxRank;
    }

    /**
     * 历届冠军列表
     * 过滤区服参与过的活动
     * @return
     */
    public static void buildChampionMsg(CrossUnionWarProto.UnionWarChampionSyncMsg msg) {
        CrossUnionWarProto.UnionWarChampionSyncMsg.Builder msgBuilder = CrossUnionWarProto.UnionWarChampionSyncMsg.newBuilder();
        long serverId = GameServer.getInstance().getServerId();
        Set<Long> serverIdSet = new HashSet<>();
        Map<String, UnionActivityRank> rankMap = new HashMap<>();
        if(msg != null){
            List<CrossUnionWarProto.UnionWarChampionListTemp> list = msg.getChampionList();
            int size = list.size();
            for(int i = 0; i < size; i++){
                CrossUnionWarProto.UnionWarChampionListTemp listTemp = list.get(i);
                CrossUnionWarProto.UnionWarChampionListTemp.Builder timeMark = CrossUnionWarProto.UnionWarChampionListTemp.newBuilder();
                timeMark.setTimeMark(listTemp.getTimeMark());
                List<CrossUnionWarProto.UnionWarChampionTemp> innerList = listTemp.getChampionList();
                int innerSize = innerList.size();
                for(int j = 0; j < innerSize; j++){
                    CrossUnionWarProto.UnionWarChampionTemp temp = innerList.get(j);
                    if(temp.getServerIdList().contains(serverId)){
                        timeMark.addChampion(temp);
                        serverIdSet.addAll(temp.getServerIdList());
                        UnionActivityRank rank = rankMap.get(temp.getUnionUid());
                        if(rank == null){
                            rank = new UnionActivityRank(temp.getActivityId(),temp.getGroupId());
                            rank.setUnionBaseInfo(CrossRankPb.parseUnionBaseInfo(temp.getUnionBaseTemp()));
                            rank.setUnionUid(temp.getUnionUid());
                            rank.setValue(BigInteger.ONE);
                            rankMap.put(temp.getUnionUid(), rank);
                        }else{
                            rank.setValue(rank.getValue().add(BigInteger.ONE));
                        }
                    }
                }
                msgBuilder.addChampion(listTemp);
            }
            if(size == 0){
                for(ActivityInfo activityInfo : getOpenActivityInfo()){
                    serverIdSet.addAll(activityInfo.getServerIdList());
                }
                championRankBuilder = UnionActivityRankProto.UnionActivityRankListMsg.newBuilder();
            }else{
                List<UnionActivityRank> rankList = new ArrayList<>();
                rankList.addAll(rankMap.values());
                rankList.sort(new UnionActivityRankSort());
                championRankBuilder = RankPb.parseUnionActivityRankListMsg( GameConfig.RANK_DEFAULT_MAX_COUNT, rankList);
            }
        }
        msgBuilder.addAllServerId(serverIdSet);
        championMsgBuilder = msgBuilder;
    }

    /**
     * 获取活动商品
     */
    public static MallInfo getActivityMallInfo(int mallId){
        MallInfo mallInfo;
        for(ActivityInfo activityInfo : activityInfoMap.values()) {
            Map<Integer, MallInfo> mallInfoMap = getActivityMallInfoMap().get(activityInfo.getActivityId());
            if (null != mallInfoMap) {
                mallInfo = mallInfoMap.get(mallId);
                if(null != mallInfo){
                    return mallInfo;
                }
            }
        }
        return null;
    }

    class ChampionUnionSort implements Comparator<UnionWarChampionUnionInfo> {
        @Override
        public int compare(UnionWarChampionUnionInfo o1, UnionWarChampionUnionInfo o2) {
            return o2.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o1.getUnionBaseInfo().getTotalEarnSpeed());
        }
    }

    /**
     * 获取现金礼包商品
     * @return
     */
    public static List<MallInfo> getRMBMallInfoList(){
        List<MallInfo> dataList = new ArrayList<>();
        List<ActivityInfo> activityInfoList = getOpenActivityInfo();
        for(ActivityInfo activityInfo : activityInfoList){
            Map<Integer, MallInfo> tempMallMap = activityMallInfoMap.get(activityInfo.getActivityId());
            if(null != tempMallMap){
                for(MallInfo mallInfo : tempMallMap.values()){
                    if(mallInfo.getCategory() == eMallCategory.UnionWarRMBMall.getValue()){
                        dataList.add(mallInfo);
                    }
                }
            }
        }
        return dataList;
    }
}
